package com.wgz.medicalmanagement.service.impl;

import com.wgz.medicalmanagement.common.entity.ChatMessage;
import com.wgz.medicalmanagement.domain.dto.ai.ChatHistoryDTO;
import com.wgz.medicalmanagement.repository.ChatMessageRepository;
import com.wgz.medicalmanagement.service.ChatHistoryService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import jakarta.transaction.Transactional;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 聊天历史服务实现类
 */
@Service
@RequiredArgsConstructor
public class ChatHistoryServiceImpl implements ChatHistoryService {
    
    private final ChatMessageRepository chatMessageRepository;
    
    /**
     * 时间格式化
     */
    private static final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern("HH:mm");
    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
    
    @Override
    public Long saveUserMessage(Long userId, String sessionId, String message) {
        ChatMessage chatMessage = ChatMessage.builder()
                .userId(userId)
                .sessionId(sessionId)
                .type("user")
                .content(message)
                .createdAt(LocalDateTime.now())
                .build();
        
        return chatMessageRepository.save(chatMessage).getId();
    }
    
    @Override
    public Long saveAiMessage(Long userId, String sessionId, String message) {
        ChatMessage chatMessage = ChatMessage.builder()
                .userId(userId)
                .sessionId(sessionId)
                .type("ai")
                .content(message)
                .createdAt(LocalDateTime.now())
                .build();
        
        return chatMessageRepository.save(chatMessage).getId();
    }
    
    @Override
    public ChatHistoryDTO getChatHistory(Long userId, String sessionId) {
        List<ChatMessage> messages = chatMessageRepository.findByUserIdAndSessionIdOrderByCreatedAtAsc(userId, sessionId);
        
        if (messages.isEmpty()) {
            return ChatHistoryDTO.builder()
                    .sessionId(sessionId)
                    .messages(List.of())
                    .lastUpdated(LocalDateTime.now())
                    .build();
        }
        
        List<ChatHistoryDTO.ChatMessageDTO> messageDTOs = messages.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
        
        LocalDateTime lastUpdated = messages.stream()
                .map(ChatMessage::getCreatedAt)
                .max(LocalDateTime::compareTo)
                .orElse(LocalDateTime.now());
        
        return ChatHistoryDTO.builder()
                .sessionId(sessionId)
                .messages(messageDTOs)
                .lastUpdated(lastUpdated)
                .build();
    }
    
    @Override
    public List<String> getUserSessionIds(Long userId) {
        return chatMessageRepository.findDistinctSessionIdByUserIdOrderByCreatedAtDesc(userId);
    }
    
    @Override
    @Transactional
    public void clearChatHistory(Long userId, String sessionId) {
        chatMessageRepository.deleteByUserIdAndSessionId(userId, sessionId);
    }
    
    @Override
    public String generateSessionId() {
        return UUID.randomUUID().toString().replace("-", "");
    }
    
    /**
     * 将数据库实体转换为DTO
     * @param message 消息实体
     * @return 消息DTO
     */
    private ChatHistoryDTO.ChatMessageDTO convertToDTO(ChatMessage message) {
        String formattedTime = formatTime(message.getCreatedAt());
        
        return ChatHistoryDTO.ChatMessageDTO.builder()
                .id(message.getId())
                .type(message.getType())
                .content(message.getContent())
                .createdAt(message.getCreatedAt())
                .formattedTime(formattedTime)
                .build();
    }
    
    /**
     * 格式化时间
     * 如果是今天的消息，只显示时间；否则显示日期和时间
     * @param dateTime 时间
     * @return 格式化后的时间字符串
     */
    private String formatTime(LocalDateTime dateTime) {
        LocalDateTime now = LocalDateTime.now();
        
        if (dateTime.toLocalDate().equals(now.toLocalDate())) {
            return "今天 " + dateTime.format(TIME_FORMATTER);
        } else {
            return dateTime.format(DATE_TIME_FORMATTER);
        }
    }
} 